{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from random import random\n",
    "from operator import add\n",
    "\n",
    "from pyspark.sql import SparkSession"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pi is roughly 3.141505\n",
      "随机坐标点个数：50000000；计算的pi值为：3.141505\n"
     ]
    }
   ],
   "source": [
    "if __name__ == \"__main__\":\n",
    "    spark = SparkSession\\\n",
    "            .builder\\\n",
    "            .appName(\"PythonPi\")\\\n",
    "            .getOrCreate()\n",
    "\n",
    "    partitions =  5\n",
    "    n = 10000000 * partitions\n",
    "\n",
    "    def f(_):\n",
    "        x = random() * 2 - 1\n",
    "        y = random() * 2 - 1\n",
    "        return 1 if x ** 2 + y ** 2 <= 1 else 0\n",
    "\n",
    "    count = spark.sparkContext.parallelize(range(1, n + 1), partitions).map(f).reduce(add)\n",
    "    print(\"Pi is roughly %f\" % (4.0 * count / n))\n",
    "    \n",
    "    pi=4.0 * count / n\n",
    "    \n",
    "    print('随机坐标点个数：%d；计算的pi值为：%f'%(n,pi))\n",
    "\n",
    "    spark.stop()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "随机坐标点个数：500000；计算的pi值为：3.136500\n"
     ]
    }
   ],
   "source": [
    "pi=3.1365 \n",
    "n =500000\n",
    "print '随机坐标点个数：%d；计算的pi值为：%f'%(n,pi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
